/**
 * 
 */
package pt.inescid.components.appadaptationlayer.applications.sumunifs;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author Sergio Esteves (sesteves at gsd.inesc-id.pt)
 *
 */
public class HandleDAT {
	public static String getConfigStr(String location) {
		try {
			FileReader fstream = new FileReader(location);
			BufferedReader in = new BufferedReader(fstream);
			String line, str = "";
			while((line = in.readLine()) != null) str = str + line + "\n";
			in.close();
			return str;
		} catch (FileNotFoundException e) {
			System.err.println("FileNotFoundException occurred: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		}
		return null;
	}
	
	public static int getKlass(String location) {
		try {
			FileReader fstream = new FileReader(location);
			BufferedReader in = new BufferedReader(fstream);
			String line;
			int i = 0;
			while((line = in.readLine()) != null) 
				if(++i == 4)
					return Integer.parseInt(line.split(" ")[2]);
			in.close();
		} catch (FileNotFoundException e) {
			System.err.println("FileNotFoundException occurred: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		}
		return -1;
	}
	
	private static double calcXLowSum(String str) {
		String[] xlow = str.split("\\s");
		double min = Integer.MAX_VALUE;
		for(String s : xlow) {
			double value = Double.parseDouble(s);
			if(value < min)
				min = value;
		}
		return 2*min;
	}
	
	private static double calcXUppSum(String str) {
		String[] xlow = str.split("\\s");
		double max = Integer.MIN_VALUE;
		for(String s : xlow) {
			double value = Double.parseDouble(s);
			if(value > max)
				max = value;
		}
		return 2*max;
	}	
	
	public static double[] getItems(String location) {
		double[] items = new double[3];
		try {
			FileReader fstream = new FileReader(location);
			BufferedReader in = new BufferedReader(fstream);
			String line;
			int i = 1;
			while((line = in.readLine()) != null) {			
				if(i == 1)
					items[0] = calcXLowSum(line);
				else if(i == 3)
					items[1] = calcXUppSum(line);
				else if(i == 4) {
					items[2] = Double.parseDouble(line.substring(0, line.indexOf(" ")));
					break;
				}
				i++;
			}
			in.close();
			return items;
		} catch (FileNotFoundException e) {
			System.err.println("FileNotFoundException occurred: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException occurred: " + e.getMessage());
		}
		return null;
	}
}
